<?php
import("com.miho.io.Session");
import("com.yamvc.application.users.UserNotFoundException");
import("com.yamvc.application.users.WrongPasswordException");
class User {
	private $_id=0;
	public function getId(){
		return $this->_id;
	}
	private $_login="Guest";
	public function getLogin(){
		return $this->_login;
	}
	private $_role=0;
	private $_userInfo;
	private $_isAuthOk=false;
	public function isAuthOk(){
		return $this->_isAuthOk;
	}
	public function __construct($login=null){
		var_dump($login);
		if($login!=null){
			$conf = Application::getAppInstance()->getConfig();
			$connection = DriverManager::getConnection($conf->get("config.db.uri"));
			$stmt = $connection->prepearStatement("SELECT * FROM sa_users WHERE login='".$login."';");
			$stmt->execute();
			$res = $stmt->getResultSet();
			if($res->getLength()>0){
				$data = $res->next();
				$this->_login=$data["login"];
				$this->_id=$data["id"];
			}else{
				throw new UserNotFoundException($login);
			}
		}else{
			//echo "USER???????";
		}
	}
	
	public function auth($password){
		$conf = Application::getAppInstance()->getConfig();
		$connection = DriverManager::getConnection($conf->get("config.db.uri"));
		$stmt = $connection->prepearStatement("SELECT role_id FROM sa_users WHERE id=".$this->_id." AND password='".$password."';");
		$stmt->execute();
		$res = $stmt->getResultSet();
		if($res->getLength()==0){
			throw new WrongPasswordException();
		}else{
			$role = $res->next();
			$this->_role = $role["role_id"];
		}
		$this->_isAuthOk=true;
		Session::instance()->activeUser=$this;
		
	}
	
	public static function getActiveUser(){
		try{
			$user = Session::instance()->activeUser;
			return $user; 
		}catch (NullPointerException $e){
			return new User(); 
		}
	}
	
	public function logout(){
		Session::instance()->activeUser = new User();
	}
	
	
}

?>